package com.pancoit.bdsdkdemo.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.pancoit.bdsdkdemo.MainApp;
import com.pancoit.bdsdkdemo.R;
import com.pancoit.bdsdkdemo.adapter.MessageListAdapter;
import com.pancoit.bdsdkdemo.base.BaseActivity;
import com.pancoit.bdsdkdemo.constant.TerminalParams;
import com.pancoit.bdsdkdemo.entity.UserMessage;
import com.pancoit.bdsdkdemo.entity.dao.SessionDao;
import com.pancoit.bdsdkdemo.entity.dao.UserMessageDao;
import com.pancoit.bdsdkdemo.entity.emums.MessageIOType;
import com.pancoit.bdsdkdemo.entity.emums.MessageStatusType;
import com.pancoit.bdsdkdemo.handler.BeidouSDKHandler;
import com.pancoit.bdsdkdemo.utils.TimeUtil;
import com.pancoit.bdsdklibrary.manage.BeidouSDKManage;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static java.lang.Thread.sleep;

/**
 * - @Description:  发送消息页
 * - @Author:  LXJ
 * - @Time:  2019/11/15 9:51
 */
public class MessageItemActivity extends BaseActivity {
    //消息列表
    @BindView(R.id.message_list_view)
    RecyclerView messageListView;
    //内容输入框
    @BindView(R.id.content_edit)
    EditText contentEdit;
    //发送按钮
    @BindView(R.id.send_btn)
    Button sendBtn;

    /*******************************************(只是单纯的强迫症想分割一下)******************************************************/
    private boolean isRefreshing = false;
    //数据
    private List<UserMessage> mListData;
    //适配器
    private MessageListAdapter adapter;
    //目标号码
    private String targetNumber;
    //位置
    private int lastPosition = 0;
    //偏移量
    private int lastOffset = 0;
    //是否滑动到底部(默认滑动到底部)
    private boolean isScrollToBottom = true;

    @Override
    public int getLayoutId() {
        return R.layout.activity_message_item;
    }

    @Override
    public void initContentView(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {
        //添加监听器
        BeidouSDKHandler.getInstance().addAgentListener(this);
        autoRefresh();
        targetNumber = getIntent().getStringExtra("target");
        initTitleBar(true, targetNumber);
        if (targetNumber == null || targetNumber.equals("")) {
            finish();
        }
        initListView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //添加监听器
        BeidouSDKHandler.getInstance().removeAgentListener(this);
        isRefreshing = false;
    }

    /**
     * 初始化列表
     */
    private void initListView() {
        mListData = new ArrayList<>();
        adapter = new MessageListAdapter(getActivity(), mListData);
        messageListView.setAdapter(adapter);
        messageListView.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        messageListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                getPositionAndOffset();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        getListData();
    }

    /**
     * 获取聊天列表数据
     */
    private void getListData() {
        mListData.clear();
        List<UserMessage> list = UserMessageDao.getInstance().getForTargetNumber(targetNumber);
        for (UserMessage userMessage : list) {
            if (userMessage.getMessageType() == MessageIOType.IN.getValue()) {
                if (userMessage.getFromNumber() != null && userMessage.getFromNumber().equals(targetNumber)) {
                    mListData.add(userMessage);
                }
            } else if (userMessage.getMessageType() == MessageIOType.OUT.getValue()) {
                if (userMessage.getToNumber() != null && userMessage.getToNumber().equals(targetNumber)) {
                    mListData.add(userMessage);
                }
            }
        }
        updateMessageList();
    }

    /**
     * 更新消息列表
     */
    private void updateMessageList() {
        getActivity().runOnUiThread(() -> {
            if (mListData != null) {
                adapter.notifyDataSetChanged();
                if (isScrollToBottom) {
                    messageListView.scrollToPosition(mListData.size() - 1);
                } else {
                    scrollToPosition();
                }
            } else {
                //todo
                //popupMsg("没有消息");
            }
        });
    }

    /**
     * 记录RecyclerView当前位置
     */
    private void getPositionAndOffset() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) messageListView.getLayoutManager();
        //获取可视的第一个view
        View topView = layoutManager.getChildAt(0);
        if (topView != null) {
            //获取与该view的顶部的偏移量
            lastOffset = topView.getTop();
            //得到该View的数组位置
            lastPosition = layoutManager.getPosition(topView);
        }
    }

    /**
     * 让RecyclerView滚动到指定位置
     */
    private void scrollToPosition() {
        if (messageListView.getLayoutManager() != null && lastPosition >= 0) {
            ((LinearLayoutManager) messageListView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
        }
    }

    /**
     * 发送消息
     */
    private void sendMessage() {
        if (!TerminalParams.isConnectNormal) {
            MainApp.getInstance().showMsg("请连接盒子");
            return;
        }
        String content = contentEdit.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            MainApp.getInstance().showMsg("请输入内容");
            return;
        }
        UserMessage userMessage = new UserMessage();
        userMessage.setToNumber(targetNumber);
        userMessage.setFromNumber(TerminalParams.cardNumber);
        userMessage.setContent(content);
        userMessage.setMessageType(MessageIOType.OUT.getValue());
        userMessage.setStatus(MessageStatusType.Unknown.getValue());
        userMessage.setTime(TimeUtil.getNowTime());
        //发送消息
        BeidouSDKManage.getInstance().sendMessage(targetNumber, content);
        //保存会话
        SessionDao.getInstance().save(targetNumber, TimeUtil.getNowTime(), content);
        //保存聊天数据
        BeidouSDKHandler.lastMsg = UserMessageDao.getInstance().save(userMessage);
        //发送状态倒计时
        BeidouSDKHandler.getInstance().startSentStatusWaitSecTimer();
        //频度倒计时
        MainApp.getInstance().startNewSentWaitSecTimer();
        contentEdit.setText("");
        getListData();
    }

    /*******************************************(只是单纯的强迫症想分割一下)******************************************************/

    @OnClick(R.id.send_btn)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_btn:
                sendMessage();
                break;
        }
    }

    /*******************************************(界面刷新)******************************************************/

    /**
     * 自动刷新
     */
    private void autoRefresh() {
        if (isRefreshing) {
            return;
        }
        isRefreshing = true;
        new Thread(() -> {
            try {
                while (isRefreshing) {
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                    sleep(1000);
                }
            } catch (Exception e) {
                Log.e("InfoMessage", e.toString());
            }
        }).start();
    }

    /**
     * 刷新UI
     */
    private Handler mHandler = new Handler(msg -> {
        switch (msg.what) {
            case 1:
                refreshUiStatus();
                break;
        }
        return false;
    });

    /**
     * 刷新界面
     */
    private void refreshUiStatus() {
        if (TerminalParams.isConnectNormal) {
            if (TerminalParams.sentWaitSec > 0) {
                sendBtn.setText(String.valueOf(TerminalParams.sentWaitSec));
                sendBtn.setClickable(false);
            } else {
                sendBtn.setText("发送");
                sendBtn.setClickable(true);
            }
        } else {
            sendBtn.setText("未连接");
            sendBtn.setClickable(false);
        }
    }

    /*******************************************(北斗2.1协议返回)******************************************************/

    @Override
    public void onCommandFeedback(String target) {
        super.onCommandFeedback(target);
        if (target.equals(targetNumber)) {
            getListData();
        }
    }

    @Override
    public void onMessageReceived(String target) {
        super.onMessageReceived(target);
        if (target.equals(targetNumber)) {
            getListData();
        }
    }
}
